package rise.ui;

import java.util.ArrayList;

import rise.comunity.Community;
import rise.comunity.Status;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;


public class MessageAdapter extends ArrayAdapter<String> {

	private String username;

	public MessageAdapter(Context context, int textViewResourceId,
			String username) {
		super(context, textViewResourceId);
		this.username = username;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.message, null);
		}
		TextView message = (TextView) convertView
				.findViewById(R.id.messageText);

		Community community = Community.obtainCommunity();

		ArrayList<String> messages = community.getMessagesFrom(this.username);
		if(messages.size() == 0)
			return convertView;
		
		message.setText(messages.get(position));

		Status status = community.getUserStatus(this.username);
		this.setStatusImage(position, messages.size(), convertView, status);

		return convertView;
	}

	private void setStatusImage(int position, int messageSize, View convertView, Status status) {
		ImageView statusImage = (ImageView) convertView
				.findViewById(R.id.senderStatus);
		if(position  != messageSize-1){
			statusImage.setImageResource(R.drawable.nullable);
			return;
		}
		
		if (status == Status.OFFLINE) {
			statusImage.setImageResource(R.drawable.invisible);
		} else if (status == Status.BUSY) {
			statusImage.setImageResource(R.drawable.busy);
		} else {
			statusImage.setImageResource(R.drawable.online);
		}
	}
}
